#include "recordlist.h"
#include <QScroller>
#include <QPainter>
#include <QPainterPath>
#include <QPen>
#include <QEvent>
#include <QMouseEvent>
#include <QScrollerProperties>
#include <QScrollBar>
#include "dataprovider.h"

RecordList::RecordList(QWidget *parent)
    :QListView(parent){
    //拖拽模式
    // setDragEnabled(true);
    // setAcceptDrops(true);
    // setDropIndicatorShown(true);
    // setDragDropMode(QAbstractItemView::InternalMove);
    setFixedWidth(268);

    setMovement(QListView::Snap);
    setVerticalScrollMode(QListView::ScrollPerPixel);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setSelectionMode(QAbstractItemView::SingleSelection);
    setAttribute(Qt::WA_AcceptTouchEvents, true);
    QScroller::grabGesture(this, QScroller::TouchGesture);
    setLayoutMode(QListView::Batched);
    // setResizeMode(QListView::Adjust);



    // int itemHeight = 50;  // 假设每个项高度为50像素
    // QScrollBar *vScrollBar = verticalScrollBar();
    // vScrollBar->setSingleStep(itemHeight);  // 每次滚动一个项的高度
    // vScrollBar->setPageStep(itemHeight);    // 每页滚动一个项的高度

    // QScroller *scroller = QScroller::scroller(this);
    // QScrollerProperties properties = QScroller::scroller(this)->scrollerProperties();
    // properties.setScrollMetric(QScrollerProperties::DecelerationFactor, 0.2);
    // scroller->setScrollerProperties(properties);

    // setUniformItemSizes(true);



    setBatchSize(50);

    setSpacing(4);

    delegate = new RecordListDelegate(this);

    setModel(&model);

    setItemDelegate(delegate);

    setStyleSheet(R"(
        QListView { border: 1px solid #DCDFE6;}
        QListView::item:hover { background: #F5F7FA; }
    )");

    QTimer::singleShot(0, [=]{
        setCurrentIndex(model.index(0));
    });

    setupConnections();
}

void RecordList::setupConnections(){
    auto dataProvider = DataProvider::instance();
    connect(dataProvider, &DataProvider::recordListUpdate, this, [=]{
        model.LoadItems();
        if (model.total > 0) {
            QTimer::singleShot(0, [=]{
                setCurrentIndex(model.index(0));
            });
        } else {
            dataProvider->SetSelectedRecord(nullptr);
        }
    });

    QItemSelectionModel *selectionModel = this->selectionModel();
    connect(selectionModel, &QItemSelectionModel::currentChanged, this, &RecordList::onItemSelected);
}

void RecordList::onItemSelected(const QModelIndex& index, const QModelIndex &previous) {
    Q_UNUSED(previous);
    auto r = model.getRecord(index);
    // qDebug() << "选择的记录：" << r->Name;
    auto dataProvider = DataProvider::instance();
    dataProvider->SetSelectedRecord(r);
}

// ********************* RecordListModel *************************/
RecordListModel::RecordListModel(QObject* parent):
    QAbstractListModel(parent) {
    total = 0;
    LoadItems();
    setupConnections();
}

int RecordListModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return records.size();
}

QVariant RecordListModel::data(const QModelIndex &index, int role) const {
    if (!index.isValid()) return QVariant();

    const auto &item = records[index.row()];

    // qDebug() << item->Name << flags(index);
    switch (role) {
    case Qt::DisplayRole:
        return item->Name;
    case MakeTime:
    {
        QDateTime makeTime = QDateTime::fromSecsSinceEpoch(item->MakeAt);
        return "制作：" + makeTime.toString("yyyy年MM月dd日 HH:mm:ss");
    }
    case VailTime:
        return "赏味期：" + item->GetValidityTimeString();
    case RecordRemark:
        return "备注：" + item->Remark;
    case IsExpired:
        return item->isExpired();
    case IsNeary:
        return item->isExpiring();
    default:
        return QVariant();
    }
}

Qt::ItemFlags RecordListModel::flags(const QModelIndex &index) const {
    return QAbstractItemModel::flags(index);
    // | Qt::ItemIsDragEnabled
    // | Qt::ItemIsDropEnabled;
}

void RecordListModel::setupConnections(){
}

void RecordListModel::LoadItems() {
    beginResetModel();
    auto dataProvider = DataProvider::instance();
    QList<Record*> list = dataProvider->GetRecords();
    records.clear();
    records = list.toVector();
    total = records.size();
    endResetModel();
}

Record* RecordListModel::getRecord(const QModelIndex &index){
    const auto &item = records[index.row()];
    return item;
}

// ********************* MaterialListDelegate *************************/
void RecordListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    QFont font;
    QRect textRect;
    QColor mainTextColor(qRgb(40, 40, 40));
    QColor otherTextColor(qRgb(80, 80, 80));

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);

    QPainterPath path;
    QPen pen;
    pen.setWidth(3);
    path.addRoundedRect(option.rect.adjusted(1, 1, -1, -1), 5, 5);

    if (option.state & QStyle::State_Selected) {
        pen.setColor(QColor(qRgb(43, 43, 115)));
        painter->setPen(pen);
        painter->drawPath(path);
        painter->fillPath(path, QColor(qRgb(75, 127, 210)));
        mainTextColor = qRgb(250, 250, 250);
        otherTextColor = qRgb(200, 200, 200);
    } else if (index.data(IsExpired).toBool()) {
        // pen.setColor(QColor(qRgb(201, 44, 44)));
        pen.setColor(QColor(qRgb(43, 43, 115)));
        painter->setPen(pen);
        painter->drawPath(path);
        painter->fillPath(path, QColor(qRgb(255, 110, 97)));
        mainTextColor = qRgb(250, 250, 250);
        otherTextColor = qRgb(230, 230, 230);
    } else if (index.data(IsNeary).toBool()){
        pen.setColor(QColor(qRgb(43, 43, 115)));
        painter->setPen(pen);
        painter->drawPath(path);
        painter->fillPath(path, QColor(qRgb(245, 135, 170)));
        mainTextColor = qRgb(250, 250, 250);
        otherTextColor = qRgb(230, 230, 230);
    } else {
        pen.setColor(QColor(qRgb(200, 200, 200)));
        painter->setPen(pen);
        painter->drawPath(path);
        painter->fillPath(path, QColor(qRgb(249, 250, 251)));
    }

    // 绘制品名
    font.setBold(true);
    font.setPointSize(9);
    textRect = option.rect.adjusted(10, 5, -5, -5);
    painter->setPen(mainTextColor);
    painter->setFont(font);
    painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap, index.data(Qt::DisplayRole).toString());

    // 绘制制作时间
    font.setBold(false);
    font.setPointSize(7);
    textRect = option.rect.adjusted(10, 28, -5, -5);
    painter->setPen(otherTextColor);
    painter->setFont(font);
    painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap, index.data(MakeTime).toString());

    // 绘制过期时间
    textRect = option.rect.adjusted(10, 48, -5, -5);
    painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap, index.data(VailTime).toString());

    // 绘制备注
    // textRect = option.rect.adjusted(10, 68, -5, -5);
    // painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap, index.data(RecordRemark).toString());

    painter->restore();
}

QSize RecordListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &) const {
    auto view = option.widget;
    int totalWidth = view->width() - view->contentsMargins().left() - view->contentsMargins().right() - 4 * 2;
    // qDebug() << "Item Size: " << totalWidth;
    return QSize(totalWidth, 80);
}


